package com.test.auth.service.impl;

import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.test.auth.entity.ComResourcesEntity;
import com.test.auth.mapper.ComResourcesMapper;
import com.test.auth.service.ComResourcesService;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;


@Service
public class ComResourcesServiceImpl implements ComResourcesService {
	
	@Autowired
	private ComResourcesMapper mapper;

	/**
	 * 保存数据（插入或更新）
	 * @param entity
	 */
	@Transactional(rollbackFor = Exception.class)
	public int save(List<ComResourcesEntity> list) {
		//查询已有数据   //更新处理
		List<ComResourcesEntity> resList = mapper.selectByCondition(null);

		Set<String> set = Sets.newHashSet();
		resList.stream().forEach(n->{
			set.add(n.getClassName() + "." + n.getMethodName());
		});

		List<ComResourcesEntity> add = Lists.newArrayList();
		List<ComResourcesEntity> update = Lists.newArrayList();
		List<ComResourcesEntity> del = Lists.newArrayList();

		Set<String> set1 = Sets.newHashSet();

		list.stream().forEach(n->{
			String key = n.getClassName() + "." + n.getMethodName();
			set1.add(key);
			if(set.contains(key)) {
				update.add(n);
			} else {
				add.add(n);
			}
		});

		resList.stream().forEach(n->{
			String key = n.getClassName() + "." + n.getMethodName();
			if(!set1.contains(key)) {
				del.add(n);
			}
		});

		if(null != add && add.size() >0) {
			mapper.batchInsert(add);
		}
		if(null != update && update.size() >0) {
			mapper.batchUpdate(update);
		}
		if(null != del && del.size() >0) {
			mapper.batchDelete(del);
		}
		return 1;

	}

	@Override
	public Set<String> getLocalPermissions() {
		List<ComResourcesEntity> resList = mapper.selectByCondition(null);

		Set<String> result = Sets.newHashSet();
		
		resList.forEach(n->{
			
			result.add(n.getPermissions());
		});

		return result;
	}


}
